package test.concurrent;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁的降级
 *
 * @author yachao.guo
 * @date 2019-06-27 16:06
 */
public class CacheData {

    Object data;
    volatile boolean cacheValid;
    final ReadWriteLock rwl = new ReentrantReadWriteLock();
    final Lock r = rwl.readLock();
    final Lock w = rwl.writeLock();


    void processCachedData() {
        r.lock();
        if (!cacheValid) {
            //释放读锁，不支持锁的升级
            r.unlock();
            w.lock();
            try {
                if (!cacheValid) {
                    //data = 赋值
                    cacheValid = true;
                }
                //释放写锁前，降级成读锁
                r.lock();
            } finally {
                w.unlock();
            }

        }
        //此处仍然持有读锁
        try {
            // 处理数据
            // use(data);
        } finally {
            r.unlock();
        }
    }

}
